import React, { Component } from 'react';
import { View, Text, StyleSheet, ScrollView, Alert, TouchableOpacity, Image, KeyboardAvoidingView, Platform, Keyboard, StatusBar } from 'react-native';
import { style } from '../../../theme/style';
import { API, API_GENERATE } from '../../../config/api';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { GLOBAL, NAVIGATIONS } from '../../../config/global';
import HTTP from '../../../utils/http';
import ToastUtil from '../../../utils/toast';
import { Common } from '../../../component/common/Common.js';
import { Header } from 'react-navigation';
import { betweenLayout } from '../create/_components/common';
import { FormItem } from '../../../components/form/formItem';
import RadioButton from '../../../components/form/radioButton';
import { Button } from '../../../components/form/button';
import ImagePicker from 'react-native-image-picker';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import { ProgressModal } from '../../../components/common/ProgressModal';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { NavigationActions } from 'react-navigation';
import Upload from '../../../utils/Upload';
const closeIcon = require('../../../imgs/close.png');
const scale = GLOBAL.SCALE;
const previewModal = {
	delTextHide: true,
	visible: false,
	uri: null,
	picPress: () => { },
	fileId: '',
}

export class RepealZXYFormPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '中新油采购成交报告-待审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
			headerRight: null,
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			},
			gesturesEnabled: false  //禁止侧滑返回事件
		}
	}

	constructor(props) {
		super(props);

		this.state = {
			status: 'data',
			imgPath: '',
			selectedKey: '1', // 1-已双签 2-未双签
			hideStatusBar: false,
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '',
				rowDataList: [],
			},
			refuseModalVisible: false
		}
		this.pageParams = {
			fileId: '',
			remark: ''
		}
		console.log('props.navigation.state.params', props.navigation.state.params)
		let { orderId, tCode, processInstanceId, formKey, taskId, businessKey } = props.navigation.state.params;
		this.tCode = tCode || '';
		this.orderId = orderId || '';
		this.formKey = formKey || '';
		this.businessKey = businessKey || '';
		this.formKey = formKey || '';
		this.taskId = taskId || ''
		this.processInstanceId = processInstanceId || ''
		this.keyboardDidShowListener = null;
		this.keyboardDidHideListener = null;
		this.scrollView = null;
		previewModal.picPress = () => {
			previewModal.visible = false;
			previewModal.uri = null;
			this.setState({ hideStatusBar: false })
		}
		this.currModalObj = {};
	}


	componentWillMount () {
		//监听键盘弹出事件
		this.keyboardDidShowListener = Keyboard.addListener('keyboardWillShow', this.keyboardWillShowHandler);
		//监听键盘隐藏事件
		this.keyboardDidHideListener = Keyboard.addListener('keyboardWillHide', this.keyboardWillHideHandler);
	}

	componentWillUnmount () {
		this.keyboardDidShowListener.remove();
		this.keyboardDidHideListener.remove();
	}

	keyboardWillShowHandler = () => {
		this.scrollView.scrollTo({ y: 120 })
	}

	keyboardWillHideHandler = () => {
		this.scrollView.scrollTo({ y: 0 })
	}

	// 切换是否合同双签章
	selectedChange = (data) => {
		this.setState({ selectedKey: data })
	}

	// 上传图片
	uploadImg = () => {
		const options = {
			title: '请选择图片来源',
			cancelButtonTitle: '取消',
			takePhotoButtonTitle: '拍照',
			chooseFromLibraryButtonTitle: '相册图片',
			quality: 1,
			maxWidth: 1080,
			maxHeight: 1080,
			storageOptions: {
				skipBackup: true,
			},
			mediaType: 'photo',
		};

		ImagePicker.showImagePicker(options, async (res) => {
			if (res && res.uri) {
				this.setState({ status: 'loading' })
				let source = { uri: res.uri }
				const uploadImgObj = {
					imgUrl: source,
					url: API_GENERATE(API.IMG_UPLOAD),
				}
				let uploadInfo = await Upload.uploadImg(uploadImgObj);
				if (uploadInfo && uploadInfo.fileId) {
					this.pageParams.fileId = uploadInfo.fileId;
					this.setState({ status: 'data', imgPath: source })
				} else {
					ToastUtil.showWarning('上传失败')
					this.setState({ status: 'data' })
				}
			}
		});
	}

	// 删除
	deleteImg = () => {
		this.pageParams.fileId = '';
		this.setState({ imgPath: '' })
	}

	// 预览图片
	previewImg = () => {
		let { imgPath } = this.state;
		previewModal.visible = true;
		previewModal.uri = imgPath.uri;
		this.setState({ hideStatusBar: true });
	}

	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}

	// 查看审批流
	getApproveProcess = async () => {
		this.setState({ status: 'loading' })
		let res = await HTTP.GET(API_GENERATE(API.ZXY_APPROVAL_PROCESS), {
			bizId: this.orderId,
			processInstanceId: this.processInstanceId
		});
		res.forEach(item => {
			if (item.taskName == '领导会签') item.taskName = '风委会成员会签'
		})
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		lightBoxData.title = '审批进度';
		lightBoxData.rowDataList = res;
		this.setState({
			lightBoxData,
			status: 'data'
		})
	}

	// 表单提交
	submit = async () => {
		let { selectedKey } = this.state;
		if (selectedKey == '1' && !this.pageParams.fileId) {
			ToastUtil.showWarning('请上传变更协议');
			return
		}
		if (selectedKey == '2' && this.pageParams.fileId) {
			this.pageParams.fileId = '';
			this.setState({ imgPath: '' })
		}
		let data = {
			businessKey: this.businessKey,
			formKey: this.formKey,
			taskId: this.taskId,
			auditResult: 1,
		}
		let requestParams = Object.assign(this.pageParams, data)
		console.log('requestParams', requestParams)
		this.setState({ refuseModalVisible: false, status: 'loading' })
		let responseData = await HTTP.POST(API_GENERATE(API.ZXY_ORDER_APPROVE), requestParams);
		if (responseData) {
			this.setState({ status: 'data' })
			ToastUtil.showSuccess('审批成功').then(() => {
				let params = { isCancel: true };
				this.tCode === 'SINONEWC' ? params.bizMode = 1 : this.tCode === 'SINONEWP' ? params.orderType = 'P' : params.orderType = 'S';
				if (GLOBAL.TAB_NAVIGATION.name !== 'HOME') GLOBAL.TAB_NAVIGATION.popToTop()
				NAVIGATIONS['HOME'].reset([NavigationActions.navigate({ routeName: 'HomePage' }),
				NavigationActions.navigate({ routeName: 'SinoNewOilApproveListPage', params })], 1);
			})
		} else {
			this.setState({ status: 'data' })
		}
	}

	openModal = async (operate, maxLength, formKey) => {
		this.currModalObj.titleText = '审批意见';
		this.currModalObj.maxLength = maxLength;
		this.currModalObj.placeholderText = `限定${maxLength}字…`;
		this.currModalObj.propsDefaultValue = '审批同意';
		this.setState({ refuseModalVisible: true });
	}

	render () {
		let { status, lightBoxData, imgPath, selectedKey, hideStatusBar } = this.state;
		let { SOrderInfo, POrderInfo, organName } = this.props.navigation.state.params;
		return (
			<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={Header.HEIGHT + 20}>
				<StatusBar
					barStyle={hideStatusBar ? 'dark-content' : 'light-content'}
					backgroundColor={hideStatusBar ? '#fff' : style.color.themeColor}
				/>
				<ScrollView
					ref={(scrollView) => { this.scrollView = scrollView }}
					style={{ flex: 1 }}
					showsVerticalScrollIndicator={false}
					keyboardShouldPersistTaps={'handled'}>
					<View style={{ backgroundColor: '#F4F7FE', paddingTop: 10 * scale }}>
						{this.tCode !== 'SINONEWS' ? betweenLayout('供应商', POrderInfo.companyName, { nofixLeft: true }) : null}
						{this.tCode !== 'SINONEWP' ? betweenLayout('客户名称', SOrderInfo.companyName, { nofixLeft: true }) : null}
						{this.tCode == 'SINONEWP' ? betweenLayout('采购给/部门', POrderInfo.organName, { nofixLeft: true }) : null}
						<View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', paddingTop: 8 * scale, paddingBottom: 12 * scale, paddingRight: 23 * scale }}>
							{
								(SOrderInfo.status == 'RPT_CANCELING' || POrderInfo.status == 'RPT_CANCELING') ? (
									<View style={styles.backoutIcon}>
										<Text style={{ color: '#fff', fontSize: 11 * scale }}>撤</Text>
									</View>
								) : null
							}
							<Text style={{ color: '#0E7FFD' }} onPress={() => { this.getApproveProcess() }}>查看审批流程</Text>
						</View>
					</View>

					<View style={{ paddingTop: 16 * scale }}>
						<FormItem required={true} rightContent={
							<View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 1 * scale }}>
								<RadioButton radioValue={'已双签'}
									radioKey={'1'}
									selectedKey={selectedKey}
									selectedChange={this.selectedChange}
								/>
								<RadioButton radioValue={'未双签'}
									radioKey={'2'}
									selectedKey={selectedKey}
									selectedChange={this.selectedChange}
								/>
							</View>
						} label='是否合同双签' />

						{
							selectedKey == '1' ? (
								<FormItem required={true} rightContent={
									<View style={{ paddingRight: 68 * scale }}>
										{imgPath ? (
											<TouchableOpacity onPress={() => { this.previewImg() }} style={{ width: 100 * scale, height: 100 * scale, position: 'relative' }}>
												<Image source={imgPath} style={{ width: '100%', height: '100%' }} />
												<TouchableOpacity activeOpacity={.8} style={styles.deleteWrap} onPress={() => { this.deleteImg() }}>
													<View style={styles.deleteIcon}>
														<Image style={{ tintColor: '#fff', width: 8 * scale, height: 8 * scale }} source={closeIcon} />
													</View>
												</TouchableOpacity>
											</TouchableOpacity>
										) : (
												<TouchableOpacity activeOpacity={.6} onPress={this.uploadImg}>
													<Text style={{ color: '#0E7FFD', fontWeight: 'bold' }}>+ 上传变更协议</Text>
												</TouchableOpacity>
											)}
									</View>
								} label='变更协议' />
							) : null
						}

						<FormItem type={'textarea'} placeHolder={'请输入备注'} label='审批备注' handleCallBack={(text) => { this.pageParams.remark = text }} />
					</View>
				</ScrollView>
				<View style={styles.btnWarp}>
					<Button text={'同意'} width={300} height={34} onPress={() => { this.openModal('Approve', 500) }} />
				</View>

				{/* 图片预览 */}
				<ModalPicDelComponent {...previewModal} />

				{/* 审批流 */}
				<ProgressModal {...lightBoxData} />

				<RefuseModal
					visible={this.state.refuseModalVisible}
					placeholderText={this.currModalObj.placeholderText}
					propsDefaultValue={this.currModalObj.propsDefaultValue}
					titleText={this.currModalObj.titleText}
					btnPress={this.submit}
					maxLength={this.currModalObj.maxLength || 500}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />

				{
					status != 'data' ? (<View style={styles.statusStyle}><PageStatusIndex status={status} /></View>) : null
				}
			</KeyboardAvoidingView >
		)
	}
}

const styles = StyleSheet.create({
	backoutIcon: {
		width: 20 * scale,
		height: 20 * scale,
		backgroundColor: '#CD4B4B',
		borderRadius: 20 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		marginRight: 10 * scale
	},
	btnWarp: {
		height: 72 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: '100%',
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
	deleteWrap: {
		position: 'absolute',
		top: -10 * scale,
		right: -10 * scale,
		width: 30 * scale,
		height: 30 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
	deleteIcon: {
		width: 18 * scale,
		height: 18 * scale,
		borderRadius: 9 * scale,
		backgroundColor: '#FD0E0E',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	}
})